package com.imooc.config;

import com.imooc.controller.interceptor.UserTokenInterceptor;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * rest请求的配置
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    /**
     * 实现静态资源的映射
     * <p>
     * windows 都是 \\ 斜杠
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("file:D:\\foodie\\images\\")      //映射本地静态资源
//                .addResourceLocations("file:/usr/alone/images/")      //映射本地静态资源
                .addResourceLocations("classpath:/META-INF/resources/");  //映射swagger2
    }

    /**
     * 注册拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //需要拦截的api列表
        List<String> pathList = Stream.of(
//                "/index/carousel",
                "/shopcart/add",
                "/shopcart/del",
                "/address/list",
                "/address/add",
                "/address/update",
                "/address/setDefalut",
                "/address/delete",
                "/orders/*",
                "/center/*",
                "/userInfo/*",
                "/myorders/*",
                "/mycomments/*").collect(Collectors.toList());

        registry.addInterceptor(userTokenInterceptor())
                .addPathPatterns(pathList)
                .excludePathPatterns("/myorders/deliver")
                .excludePathPatterns("/order/notifyMerchantOrderPaid");

        WebMvcConfigurer.super.addInterceptors(registry);
    }

    @Bean
    public UserTokenInterceptor userTokenInterceptor() {
        return new UserTokenInterceptor();
    }
}
